<template>
	<view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="nav-title">分类管理</text>
        <view class="nav-right" @click="goToAddCategory">
          <text class="add-icon">+</text>
        </view>
      </view>
    </view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <scroll-view 
        scroll-y 
        class="category-scroll"
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="refreshData"
      >
        <!-- 分类列表 -->
        <view class="category-list">
          <view 
            class="category-item" 
            v-for="category in categories" 
            :key="category.id"
            @click="editCategory(category)"
            @longpress="showCategoryMenu(category)"
          >
            <!-- 分类头部 -->
            <view class="category-header">
              <view class="header-left">
                <view class="category-info">
                  <view class="category-icon-wrapper" :style="{ backgroundColor: category.color + '20' }">
                    <text class="category-icon">{{ category.icon || '📁' }}</text>
                  </view>
                  <view class="category-details">
                    <text class="category-name">{{ category.name }}</text>
                    <text class="category-desc" v-if="category.description">
                      {{ category.description }}
                    </text>
                  </view>
                </view>
              </view>
              <view class="header-right">
                <text class="more-icon" @click.stop="showCategoryMenu(category)">⋯</text>
              </view>
            </view>
            
            <!-- 分类统计 -->
            <view class="category-stats">
              <view class="stats-row">
                <view class="stat-item">
                  <text class="stat-icon">📝</text>
                  <text class="stat-text">{{ category.diaryCount || 0 }} 篇日记</text>
                </view>
                <view class="stat-item">
                  <text class="stat-icon">📅</text>
                  <text class="stat-text">创建于 {{ formatDate(category.createdAt) }}</text>
                </view>
              </view>
            </view>
            
            <!-- 分类颜色条 -->
            <view class="category-color-bar" :style="{ backgroundColor: category.color }"></view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="categories.length === 0 && !loading">
          <text class="empty-icon">📂</text>
          <text class="empty-title">暂无分类</text>
          <text class="empty-desc">创建你的第一个分类，让日记更有条理</text>
          <button class="empty-btn" @click="goToAddCategory">创建分类</button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 悬浮按钮 -->
    <view class="fab-container">
      <view class="fab-btn" @click="goToAddCategory">
        <text class="fab-icon">+</text>
      </view>
    </view>
    
    <!-- 分类操作菜单 -->
    <view class="modal-overlay" v-if="showActionModal" @click="showActionModal = false">
      <view class="action-modal" @click.stop>
        <view class="action-item" @click="editCategory(selectedCategory)">
          <text class="action-text">编辑分类</text>
        </view>
        <view class="action-item" @click="viewCategoryDiaries(selectedCategory)">
          <text class="action-text">查看日记</text>
        </view>
        <view class="action-item delete" @click="deleteCategory(selectedCategory)">
          <text class="action-text">删除分类</text>
        </view>
        <view class="action-item cancel" @click="showActionModal = false">
          <text class="action-text">取消</text>
        </view>
      </view>
    </view>
    
    <!-- 底部导航栏 -->
    <TabBar :current="3" />
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <text class="loading-text">⏳</text>
      <text class="loading-desc">加载中...</text>
    </view>
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { getCategoriesAPI, deleteCategoryAPI } from '@/api/category'
import { formatDate } from '@/utils/index'
import TabBar from '@/components/TabBar.vue'
import { extractResponseData } from '@/utils/index'

export default {
  name: 'CategoryListPage',
  components: {
    TabBar
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore,
      formatDate
    }
  },
  data() {
    return {
      categories: [],
      loading: false,
      refreshing: false,
      showActionModal: false,
      selectedCategory: null,
      isLoadingCategories: false
    }
  },
  
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    }
  },
  onLoad() {
    this.initPage()
  },
  onShow() {
    // 只有在分类列表为空时才刷新
    if (this.categories.length === 0 && this.userStore.isLogin) {
      this.loadCategories()
    }
  },
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 加载分类列表
      await this.loadCategories()
    },
    
    async loadCategories() {
      if (this.isLoadingCategories) return
      
      this.loading = true
      this.isLoadingCategories = true
      
      try {
        const res = await getCategoriesAPI()
        const responseData = extractResponseData(res)
        this.categories = responseData || []
        
        // 更新状态管理中的分类数据
        this.diaryStore.setCategories(this.categories)
        
      } catch (error) {
        console.error('加载分类失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.isLoadingCategories = false
      }
    },
    
    async refreshData() {
      this.refreshing = true
      await this.loadCategories()
      this.refreshing = false
    },
    
    // 显示分类操作菜单
    showCategoryMenu(category) {
      this.selectedCategory = category
      this.showActionModal = true
    },
    
    // 编辑分类
    editCategory(category) {
      if (!category) return
      this.showActionModal = false
      uni.navigateTo({
        url: `/pages/category/edit?id=${category.id}`
      })
    },
    
    // 查看分类日记
    viewCategoryDiaries(category) {
      if (!category) return
      this.showActionModal = false
      uni.switchTab({
        url: '/pages/diary/list',
        success: () => {
          // 设置筛选条件
          this.diaryStore.setFilters({ categoryId: category.id })
        }
      })
    },
    
    // 删除分类
    async deleteCategory(category) {
      if (!category) return
      
      const result = await uni.showModal({
        title: '确认删除',
        content: `确定要删除分类"${category.name}"吗？删除后该分类下的日记将不再归类。`,
        confirmText: '删除',
        confirmColor: '#ff4d4f'
      })
      
      if (!result.confirm) return
      
      try {
        await deleteCategoryAPI(category.id)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.showActionModal = false
        this.loadCategories()
      } catch (error) {
        console.error('删除分类失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    },
    
    // 跳转到添加分类页面
    goToAddCategory() {
      uni.navigateTo({
        url: '/pages/category/edit'
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height, 44rpx);
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 40rpx;
  height: 88rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.nav-right {
  padding: 8rpx;
}

.add-icon {
  font-size: 40rpx;
  color: #ffffff;
  font-weight: bold;
}

.page-content {
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  padding-left: 40rpx;
  padding-right: 40rpx;
  padding-bottom: 160rpx;
}

.category-scroll {
  height: 100%;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.category-item {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
  position: relative;
  overflow: hidden;
}

.category-item:active {
  transform: scale(0.98);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
}

.header-left {
  flex: 1;
  margin-right: 16rpx;
}

.category-info {
  display: flex;
  align-items: center;
}

.category-icon-wrapper {
  width: 120rpx;
  height: 120rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.category-icon {
  font-size: 48rpx;
}

.category-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.category-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.category-desc {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.4;
}

.header-right {
  padding: 8rpx;
}

.more-icon {
  font-size: 32rpx;
  color: #cccccc;
}

.category-stats {
  margin-bottom: 16rpx;
}

.stats-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 32rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex: 1;
}

.stat-icon {
  font-size: 24rpx;
}

.stat-text {
  font-size: 24rpx;
  color: #999999;
}

.category-color-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 8rpx;
  border-radius: 0 0 24rpx 24rpx;
}

.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  display: block;
}

.empty-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 16rpx;
  display: block;
}

.empty-desc {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 48rpx;
  display: block;
}

.empty-btn {
  background-color: #1890ff;
  color: #ffffff;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
}

.empty-btn::after {
  border: none;
}

.fab-container {
  position: fixed;
  right: 40rpx;
  bottom: 200rpx;
  z-index: 999;
}

.fab-btn {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
}

.fab-icon {
  font-size: 48rpx;
  color: #ffffff;
  font-weight: bold;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-modal {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 40rpx;
  overflow: hidden;
}

.action-item {
  padding: 32rpx 40rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item.delete .action-text {
  color: #ff4d4f;
}

.action-item.cancel {
  margin-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-text {
  font-size: 32rpx;
  color: #333333;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 1500;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}

.loading-text {
  font-size: 48rpx;
}

.loading-desc {
  font-size: 28rpx;
  color: #666666;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .nav-bar {
  background: linear-gradient(135deg, #404040 0%, #2d2d30 100%);
}

.theme-dark .category-item {
  background-color: #252526;
}

.theme-dark .category-name,
.theme-dark .empty-title {
  color: #e8e8e8;
}

.theme-dark .category-desc,
.theme-dark .stat-text,
.theme-dark .empty-desc,
.theme-dark .loading-desc {
  color: #b3b3b3;
}

.theme-dark .more-icon {
  color: #8c8c8c;
}

.theme-dark .fab-btn {
  background: linear-gradient(135deg, #404040 0%, #2d2d30 100%);
}

.theme-dark .action-modal {
  background-color: #252526;
}

.theme-dark .action-text {
  color: #e8e8e8;
}

.theme-dark .action-item {
  border-bottom-color: #404040;
}

.theme-dark .action-item.cancel {
  border-top-color: #404040;
}

.theme-dark .loading-overlay {
  background-color: rgba(30, 30, 30, 0.8);
}
</style> 